package com.jin10.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jin10.bean.Jin10CalendarResponse;
import com.jin10.dto.ParagraphDto;
import com.jin10.entity.ApiList;
import com.jin10.entity.SentenceLibrary;
import com.jin10.entity.Tag;
import com.jin10.mapper.SentenceLibraryMapper;
import com.jin10.service.ISentenceLibraryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jin10.service.ITagService;
import com.jin10.vo.TagTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 标签句子库 服务实现类
 * </p>
 *
 * @author raofy
 * @since 2022-01-20
 */
@Service
public class SentenceLibraryServiceImpl extends ServiceImpl<SentenceLibraryMapper, SentenceLibrary> implements ISentenceLibraryService {

    @Autowired
    ITagService iTagService;


//    @Override
//    public Object getSentenceLibraryByTag(ParagraphDto dto) {
//        Map<Integer, Object> map = new HashMap<>();
//        if (dto.getTagIds().isEmpty()) {
//            return map;
//        } else {
//            // 从现有库中查询匹配段落
//            Map<Integer, List<SentenceLibrary>> fromLibrary = getParagraphFromLibrary(dto.getTagIds());
//            if (fromLibrary.isEmpty()) {
//                return map;
//            } else {
//                List<Integer> emptyList = new ArrayList<>();
//                for (Map.Entry<Integer, List<SentenceLibrary>> entry : fromLibrary.entrySet()) {
//                    Integer tagId = entry.getKey();
//                    List<SentenceLibrary> value = entry.getValue();
//                    if (value.isEmpty()) {
//                        emptyList.add(tagId);
//                        continue;
//                    } else {
//                        map.put(tagId, value.get(0).getSentence());
//                    }
//                }
//                return map;
//            }
//        }
//
//    }

    @Override
    public Object getSentenceByTag(ParagraphDto dto) {
        List<TagTreeVo> result = new ArrayList<>();

        if (dto.getTagIds().isEmpty()) {
            return result;
        } else {
            List<Integer> rootTagId = dto.getTagIds();
            // 遍历查询出所有子标签
            for (Integer tagId : rootTagId) {
                TagTreeVo rootTag = iTagService.getTagListByRootId(tagId);
                if (rootTag != null) {
                    result.add(getSentence(rootTag));
                }
            }
        }
        return result;
    }


    @Override
    public Object getSentenceById(Integer id) {
        StringBuffer result = new StringBuffer();
        LambdaUpdateWrapper<SentenceLibrary> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(SentenceLibrary::getTagId, id);
        List<SentenceLibrary> sentenceLibraries = baseMapper.selectList(wrapper);
        if (!sentenceLibraries.isEmpty()) {
            // 随机返回一个句子
            int maxSize = sentenceLibraries.size();
            Random random = new Random();
            int index = random.nextInt(maxSize);
            result.append(sentenceLibraries.get(index).getSentence());
        }
        return result.toString();
    }

    public TagTreeVo getSentence(TagTreeVo vo) {
        if (Objects.nonNull(vo)) {
            List<TagTreeVo> subclass = vo.getSubclass();
            if (!subclass.isEmpty()) {
                for (TagTreeVo tagTreeVo : subclass) {
                    getSentence(tagTreeVo);
                }
            }
            vo.setTitle(getSentenceByMethod(vo));
        }

        return vo;
    }


    /**
     * 返回短句
     *
     * @param vo
     * @return
     */
    public String getSentenceByMethod(TagTreeVo vo) {
        StringBuffer result = new StringBuffer();
        // 从资料库获取
        LambdaUpdateWrapper<SentenceLibrary> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(SentenceLibrary::getTagId, vo.getId());
        List<SentenceLibrary> sentenceLibraries = baseMapper.selectList(wrapper);
        if (!sentenceLibraries.isEmpty()) {
            // 随机返回一个句子
            int maxSize = sentenceLibraries.size();
            Random random = new Random();
            int index = random.nextInt(maxSize);
            result.append(sentenceLibraries.get(index).getSentence());
        }

        // 通过api方式获取
        if (!vo.getApis().isEmpty()) {
            List<ApiList> apis = vo.getApis();
            for (ApiList element : apis) {
                String api = element.getApi();
                Map headers = JSON.parseObject(element.getRequestHeader(), HashMap.class);
                HashMap param = JSON.parseObject(element.getRequestParam(), HashMap.class);
                HttpResponse response = HttpRequest.get(api).headerMap(headers, false).form(param).execute();
                Jin10CalendarResponse jin10CalendarResponse = JSON.parseObject(response.body(), Jin10CalendarResponse.class);
                Jin10CalendarResponse.DataBean dataBean = jin10CalendarResponse.getData().get(0);
                String format = String.format("%s%s%s(%s),前值%s，预测值%s，实际值%s", dataBean.getCountry(), dataBean.getTimePeriod(), dataBean.getName(), dataBean.getUnit(), dataBean.getRevised(), dataBean.getConsensus(), dataBean.getActual());
                if (StrUtil.isBlank(result.toString())) {
                    result.append(format);
                } else {
                    result.append("," + format);
                }
            }
        }

        // 通过模板进行替换
        return result.toString();
    }


    public Map<Integer, List<SentenceLibrary>> getParagraphFromLibrary(List<Integer> tagIds) {
        Map<Integer, List<SentenceLibrary>> result = new HashMap<>();
        LambdaUpdateWrapper<SentenceLibrary> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(SentenceLibrary::getTagId, tagIds);
        List<SentenceLibrary> sentenceLibraries = baseMapper.selectList(wrapper);
        if (!sentenceLibraries.isEmpty()) {
            result = sentenceLibraries.stream().collect(Collectors.groupingBy(SentenceLibrary::getTagId));
        }
        return result;
    }


}


